﻿using System;
using System.IO;
using System.Xml;
using System.Data;
using System.Configuration;
using System.Web;
using System.Collections.Specialized;
using SyCODE.Component;
using SyCODE.Component.Security;
using System.Web.Security;

namespace SyCODE.Blog
{
    /// <summary>
    /// SetCollection 的摘要说明
    /// </summary>
    public class SetCollection : IHttpHandler
    {
        private string bloger = String.Empty;
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
			Ticket ticket = Ticket.Get(FormsAuthentication.FormsCookieName);
            if (Ticket.Authenticate(ticket))
            {
                bloger = ticket.Name;

                string path = Path.Combine(AppPath.GetUserPhysicalPath(bloger), "collection.xml");

                XmlDocument collctionDom = new XmlDocument();

                switch (context.Request.Form["active"])
                {
                    case "0":
                        collctionDom.Load(path);
                        context.Response.Write(AddCollection(collctionDom, context.Request.Form["name"]));
                        break;
                    case "1":
                        collctionDom.Load(path);
                        RenameCollection(collctionDom, context.Request.Form["idx"], context.Request.Form["name"]);
                        break;
                    case "2":
                        collctionDom.Load(path);
                        RemoveCollection(collctionDom, context.Request.Form["idx"]);
                        break;
                    case "3":
                        collctionDom.Load(path = Path.Combine(AppPath.GetUserPhysicalPath(bloger), context.Request.Form["collection"]));
                        AddItem(collctionDom, context.Request.Form["title"], context.Request.Form["href"], context.Request.Form["describe"]);
                        break;
                    case "4":
                        collctionDom.Load(path = Path.Combine(AppPath.GetUserPhysicalPath(bloger), context.Request.Form["collection"]));
                        ChangeItem(collctionDom, context.Request.Form["item"], context.Request.Form["title"], context.Request.Form["href"], context.Request.Form["describe"]);
                        break;
                    case "5":
                        collctionDom.Load(path = Path.Combine(AppPath.GetUserPhysicalPath(bloger), context.Request.Form["collection"]));
                        DeleteItem(collctionDom, context.Request.Form["item"]);
                        break;
                }

                collctionDom.Save(path);
            }
            else
            {
                Function.ClientAlert(StringResource.GetField("authfaild"));
            }
        }

        private string AddCollection(XmlDocument collctionDom, string name)
        {
            string tick = DateTime.Now.Ticks.ToString();
            string local = "collection/" + tick + ".xml";
            string path = Path.Combine(AppPath.GetUserPhysicalPath(bloger), local);


            XmlElement collction = collctionDom.CreateElement("a");
            collction.SetAttribute("href", local);
            collction.InnerText = name;

            collctionDom.DocumentElement.SelectSingleNode("body").AppendChild(collction);

            XmlTextWriter writer = new XmlTextWriter(File.Create(path), HttpContext.Current.Response.ContentEncoding);
            writer.WriteStartDocument();
            writer.WriteProcessingInstruction("xml-stylesheet", "type='text/xsl' href='/ui/common/collection.xsl'");

            writer.WriteStartElement("html");

            writer.WriteStartElement("head");

            writer.WriteStartElement("meta");
            writer.WriteAttributeString("http-equiv", "Content-Type");
            writer.WriteAttributeString("content", "text/html; charset=" + HttpContext.Current.Response.ContentEncoding.WebName);
            writer.WriteEndElement();

            writer.WriteStartElement("title");
            writer.WriteString(name + " - Powered By X3BLOG");
            writer.WriteEndElement();

            writer.WriteEndElement();

            writer.WriteStartElement("body");
            writer.WriteEndElement();

            writer.WriteEndElement();
            writer.WriteEndDocument();

            writer.Flush();
            writer.Close();

            return local;
        }

        private void RenameCollection(XmlDocument collctionDom, string idx, string name)
        {
            XmlNode collction = collctionDom.DocumentElement.SelectSingleNode("body").ChildNodes[Int32.Parse(idx)];
            collction.InnerText = name;
            string collectionPath = Path.Combine(AppPath.GetUserPhysicalPath(bloger), collction.Attributes["href"].Value);
            XmlDocument itemDom = new XmlDocument();
            itemDom.Load(collectionPath);

            itemDom.DocumentElement.SelectSingleNode("head/title").InnerText = name;

            itemDom.Save(collectionPath);
        }

        private void RemoveCollection(XmlDocument collctionDom, string idx)
        {
            XmlNode collction = collctionDom.DocumentElement.SelectSingleNode("body").ChildNodes[Int32.Parse(idx)];

            string path = Path.Combine(AppPath.GetUserPhysicalPath(bloger), collction.Attributes["href"].Value);
            if(File.Exists(path))
            {
                File.Delete(path);
            }

            collction.ParentNode.RemoveChild(collction);
        }

        private void AddItem(XmlDocument collctionDom, string title, string href, string describe)
        {
            XmlElement collction = collctionDom.CreateElement("p");

            XmlElement link = collctionDom.CreateElement("a");
            link.SetAttribute("href", href);
            link.InnerText = title;
            collction.AppendChild(link);

            XmlElement text = collctionDom.CreateElement("p");
            text.InnerText = describe;
            collction.AppendChild(text);

            collctionDom.DocumentElement.SelectSingleNode("body").AppendChild(collction);
        }

        private void ChangeItem(XmlDocument collctionDom, string idx, string title, string href, string describe)
        {
            XmlElement collction = (XmlElement)collctionDom.DocumentElement.SelectSingleNode("body").ChildNodes[Int32.Parse(idx)];
            collction.FirstChild.Attributes["href"].Value = href;
            collction.FirstChild.InnerText = title;
            collction.LastChild.InnerText = describe;
        }

        private void DeleteItem(XmlDocument collctionDom, string idx)
        {
            XmlNode item = collctionDom.DocumentElement.SelectSingleNode("body");
            item.RemoveChild(item.ChildNodes[Int32.Parse(idx)]);
        }
    }
}